<template>
  <div class="app-container">
    <el-form
      class="search-form"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品SPU" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入商品SPU名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品分类" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入商品分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="销售价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入销售价格"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品成本价" prop="costPrice">
        <el-input
          v-model="queryParams.costPrice"
          placeholder="请输入商品成本价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否上架" prop="isActive">
        <el-radio-group v-model="queryParams.isActive">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['transaction:sku:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['transaction:sku:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['transaction:sku:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['transaction:sku:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="skuList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU ID" align="center" prop="id" />
      <el-table-column label="商品名称SPU" align="center" prop="spuName" />
      <el-table-column label="商品分类" align="center" prop="categoryName" />
      <el-table-column label="规格信息" align="center" prop="spec" width="200">
        <template #default="scope">
          <div v-if="scope.row.spec">
            <el-tag
              v-for="(value, key) in parseSpecJson(scope.row.spec)"
              :key="key"
              size="small"
              type="info"
              style="margin: 2px;"
            >
              {{ key }}: {{ value }}
            </el-tag>
          </div>
          <span v-else style="color: #999;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="商品条形码" align="center" prop="barcode" />
      <el-table-column label="销售价格" align="center" prop="price" />
      <el-table-column label="商品成本价" align="center" prop="costPrice" />
      <el-table-column
        label="商品展示图"
        align="center"
        prop="imageUrl"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="是否上架" align="center" prop="isActive">
        <template #default="{ row }">
          <el-tag
            :type="row.isActive == 1 ? 'success' : 'info'"
            size="small"
            effect="light"
          >
            {{ row.isActive == 1 ? '已上架' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['transaction:sku:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['transaction:sku:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品SKU对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="skuRef" :model="form" :rules="rules" label-width="120px">
        
        <!-- SPU选择 -->
        <el-form-item label="选择商品SPU" prop="spuId" required>
          <el-select
            v-model="form.spuId"
            placeholder="请选择商品SPU"
            @change="handleSpuChange"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="spu in spuOptions"
              :key="spu.id"
              :label="`${spu.name} (${spu.brandName})`"
              :value="spu.id"
            />
          </el-select>
        </el-form-item>

        <!-- 动态规格值选择 -->
        <el-form-item 
          v-for="spec in selectedSpuSpecs" 
          :key="spec.id"
          :label="spec.name" 
          :prop="`specValues.${spec.id}`"
          required
        >
          <el-select
            v-model="form.specValues[spec.id]"
            :placeholder="`请选择${spec.name}`"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="specValue in spec.specValues"
              :key="specValue.id"
              :label="specValue.value"
              :value="specValue.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品条形码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入商品条形码" />
        </el-form-item>
        
        <el-form-item label="销售价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入销售价格" />
        </el-form-item>
        
        <el-form-item label="商品成本价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入商品成本价" />
        </el-form-item>
        
        <el-form-item label="商品展示图URL" prop="imageUrl">
          <image-upload v-model="form.imageUrl" />
        </el-form-item>
        
        <el-form-item label="是否上架" prop="isActive">
          <el-radio-group v-model="form.isActive">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sku">
import {
  listSku,
  getSku,
  delSku,
  addSku,
  updateSku,
} from "@/api/transaction/sku";

import {
  listSpuVo,
  getSpu,
  delSpu,
  addSpu,
  updateSpu,
  getAllSpuWithSpecs
} from "@/api/transaction/spu";
import { listSpec, getSpec, delSpec, addSpec, updateSpec } from "@/api/transaction/spec"
import { listValue, getValue, delValue, addValue, updateValue } from "@/api/transaction/value"

const { proxy } = getCurrentInstance();

const skuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 新增的数据
const spuOptions = ref([]); // SPU选项
const selectedSpuSpecs = ref([]); // 当前选中SPU的规格列表

const data = reactive({
  form: {
    id: null,
    spuId: null,
    spec: null,
    barcode: null,
    price: null,
    costPrice: null,
    imageUrl: null,
    isActive: 1,
    delFlag: null,
    createTime: null,
    updateTime: null,
    specValues: {}, // 存储选择的规格值
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    spuName: null,
    categoryName: null,
    spec: null,
    barcode: null,
    price: null,
    costPrice: null,
    isActive: null,
  },
  rules: {
    spuId: [
      { required: true, message: "请选择商品SPU", trigger: "change" }
    ],
    price: [
      { required: true, message: "请输入销售价格", trigger: "blur" }
    ],
    costPrice: [
      { required: true, message: "请输入商品成本价", trigger: "blur" }
    ]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 解析规格信息JSON字符串 */
function parseSpecJson(specString) {
  try {
    return JSON.parse(specString);
  } catch (error) {
    console.error('解析规格信息失败:', error);
    return {};
  }
}

/** 查询商品SKU列表 */
function getList() {
  loading.value = true;
  listSku(queryParams.value).then((response) => {
    skuList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取所有SPU及其规格信息 */
function getSpuOptions() {
  return getAllSpuWithSpecs().then((response) => {
    spuOptions.value = response.data;
    return response.data;
  });
}

/** SPU选择变化处理 */
function handleSpuChange(spuId) {
  console.log('handleSpuChange 被调用，spuId:', spuId);
  console.log('当前form数据:', form.value);
  console.log('form.value.id:', form.value.id);
  console.log('form.value.spec:', form.value.spec);
  console.log('form.value.spec类型:', typeof form.value.spec);
  
  if (!spuId) {
    selectedSpuSpecs.value = [];
    form.value.specValues = {};
    form.value.spec = '';
    return;
  }

  // 找到选中的SPU
  const selectedSpu = spuOptions.value.find(spu => spu.id === spuId);
  console.log('找到的SPU:', selectedSpu);
  
  if (selectedSpu && selectedSpu.specDTOList) {
    selectedSpuSpecs.value = selectedSpu.specDTOList;
    console.log('设置的规格列表:', selectedSpuSpecs.value);
    
    // 如果是修改模式，先解析现有规格信息
    const hasValidSpec = form.value.id && form.value.spec && form.value.spec !== '{}' && form.value.spec !== 'null';
    console.log('hasValidSpec:', hasValidSpec);
    
    if (hasValidSpec) {
      console.log('检测到修改模式，解析规格信息:', form.value.spec);
      let specObject = {};
      
      try {
        // 处理spec可能是字符串或对象的情况
        if (typeof form.value.spec === 'string') {
          specObject = JSON.parse(form.value.spec);
        } else if (typeof form.value.spec === 'object') {
          specObject = form.value.spec;
        }
        
        console.log('解析后的规格对象:', specObject);
        form.value.specValues = {};
        selectedSpuSpecs.value.forEach(spec => {
          const specValue = specObject[spec.name] || '';
          form.value.specValues[spec.id] = specValue;
          console.log(`设置规格 ${spec.name} (ID: ${spec.id}) = ${specValue}`);
        });
        console.log('最终设置的规格值:', form.value.specValues);
      } catch (error) {
        console.error('解析现有规格信息失败:', error);
        // 如果解析失败，初始化空值
        form.value.specValues = {};
        selectedSpuSpecs.value.forEach(spec => {
          form.value.specValues[spec.id] = '';
        });
      }
    } else {
      console.log('新增模式或没有规格信息');
      // 新增模式，初始化空值
      form.value.specValues = {};
      selectedSpuSpecs.value.forEach(spec => {
        form.value.specValues[spec.id] = '';
      });
    }
  } else {
    console.log('未找到SPU或SPU没有规格信息');
    selectedSpuSpecs.value = [];
    form.value.specValues = {};
  }
  
  // 只有在新增时才清空规格信息
  if (!form.value.id) {
    form.value.spec = '';
  }
}

/** 监听规格值变化，自动生成规格信息 */
watch(() => form.value.specValues, (newSpecValues) => {
  const specObject = {};
  selectedSpuSpecs.value.forEach(spec => {
    if (newSpecValues[spec.id]) {
      specObject[spec.name] = newSpecValues[spec.id];
    }
  });
  form.value.spec = JSON.stringify(specObject);
}, { deep: true });

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    spuId: null,
    spec: null,
    barcode: null,
    price: null,
    costPrice: null,
    imageUrl: null,
    isActive: 1,
    delFlag: null,
    createTime: null,
    updateTime: null,
    specValues: {},
  };
  selectedSpuSpecs.value = [];
  proxy.resetForm("skuRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品SKU";
  // 获取SPU选项
  getSpuOptions();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getSku(_id).then((response) => {
    // 使用 Object.assign 来保持响应式
    Object.assign(form.value, response.data);
    console.log('加载的SKU数据:', form.value);
    console.log('SKU数据的spec字段:', form.value.spec);
    console.log('spec字段的类型:', typeof form.value.spec);
    console.log('spec字段的内容:', JSON.stringify(form.value.spec));
    open.value = true;
    title.value = "修改商品SKU";
    // 获取SPU选项
    getSpuOptions().then(() => {
      // 等待SPU选项加载完成后再设置规格值
      if (form.value.spuId) {
        console.log('准备设置SPU:', form.value.spuId);
        console.log('当前规格信息:', form.value.spec);
        // 确保spec数据已经设置
        if (form.value.spec && form.value.spec !== '{}' && form.value.spec !== 'null') {
          // handleSpuChange 会自动处理规格值的设置
          handleSpuChange(form.value.spuId);
        } else {
          console.error('spec数据未正确设置');
        }
      }
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["skuRef"].validate((valid) => {
    if (valid) {
      // 验证是否选择了所有必需的规格值
      const missingSpecs = selectedSpuSpecs.value.filter(spec => 
        !form.value.specValues[spec.id]
      );
      
      if (missingSpecs.length > 0) {
        proxy.$modal.msgError(`请选择以下规格值：${missingSpecs.map(s => s.name).join('、')}`);
        return;
      }

      if (form.value.id != null) {
        updateSku(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSku(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品SKU编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delSku(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "transaction/sku/export",
    {
      ...queryParams.value,
    },
    `sku_${new Date().getTime()}.xlsx`
  );
}

getList();

</script> 

<style scoped>
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 控制间距 */
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0; /* 去掉多余的竖直间距 */
}

.search-form .el-input {
  width: 200px; /* 每个输入框固定宽度 */
}
</style>
